import { createApp } from 'vue';

import { registerAccessDirective } from '@vben/access';
import { initStores } from '@vben/stores';
import '@vben/styles';
import '@vben/styles/ele';

import { setupI18n } from '#/locales';

import { initComponentAdapter } from './adapter/component';
import App from './app.vue';
import { router } from './router';
import currentUrl from './utils/currentUrl';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import './utils/main.css';



import { logoutApi } from "./api/core/auth.ts"
axios.interceptors.request.use(
  function (config) {
    // 动态从 localStorage 查找 accessToken
    let accessToken = '';
    for (const key in localStorage) {
      if (key.includes('access')) { // 更安全的键名匹配方式
        try {
          const storedData = localStorage.getItem(key);
          if (storedData) {
            accessToken = JSON.parse(storedData).accessToken;
            break;
          }
        } catch (error) {
          console.error('解析 localStorage 数据失败:', error);
        }
      }
    }

    // 将 token 直接注入当前请求的 headers
    if (accessToken) {
      config.headers.Authorization = `${accessToken}`;
    } else {
      console.warn('未找到有效的 accessToken');
    }

    return config;
  },
  function (error) {


    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {




  if (error.status == 401) {
    logoutApi()
    for (const key in localStorage) {
      if (key.includes('access')) { // 更安全的键名匹配方式
        localStorage.removeItem(key);
      }
    }
    router.replace('/auth/login')
  }
  return Promise.reject(error);
});

if (import.meta.env.MODE == 'production') {
  console.log = () => { };
}

import QueryForm from './components/QueryForm.vue';
import Pagination from './components/Pagination.vue';

import axios from 'axios';







async function bootstrap(namespace: string) {
  // 初始化组件适配器
  await initComponentAdapter();
  const app = createApp(App);
  app.config.globalProperties.$currentUrl = currentUrl;
  // 国际化 i18n 配置
  await setupI18n(app);

  // 配置 pinia-tore
  await initStores(app, { namespace });

  // 安装权限指令
  registerAccessDirective(app);

  // 配置路由及路由守卫
  app.use(router);

  app.use(ElementPlus);

  app.component('QueryForm', QueryForm);
  app.component('Pagination', Pagination);
  app.mount('#app');
}

export { bootstrap };
